package com.kinon.ceshiaccount.wxpay;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.BaseActivity;
import com.kinon.ceshiaccount.activity.PayresultActivity;
import com.kinon.ceshiaccount.bean.base.Balance;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.urgent.U_SettletmentBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SysTimeManage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Response;
import sunmi.ds.callback.ISendCallback;

import static com.kinon.ceshiaccount.wxpay.WxPay.spbill_create_ip;

/**
 * Created by luohao on 2017-08-01.
 * 结算生成的订单界面，负责刷卡支付
 */

public class WxOrderPayActivity extends BaseActivity implements View.OnClickListener {
    /**返回*/
    private TextView tv_back;
    /**显示收款金额*/
    private TextView tv_orderTotal;
    /**接收卡号*/
    private EditText et_pay;
    private String id="";
    int diningType;

    private String total="0.0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderpay_layout);
        initView();
    }

    private void initView() {
        tv_back= (TextView) findViewById(R.id.tv_back);
        tv_orderTotal= (TextView) findViewById(R.id.tv_orderTotal);
        et_pay= (EditText) findViewById(R.id.et_pay);
         total=getIntent().getStringExtra("total");
         id=getIntent().getStringExtra("oridrid");
        diningType=getIntent().getIntExtra("diningType",0);
        tv_orderTotal.setText(String.valueOf(total));
        tv_back.setOnClickListener(this);


        et_pay.addTextChangedListener(tWatcher);
        SunmiSdkManage.getInstance().showPrice(getString(R.string.pleasePay),total+"",
                null);
    }



   private ISendCallback callback=new ISendCallback() {
       @Override
       public void onSendSuccess(long taskId) {
           myHandler.postDelayed(delayRun,1000);
//           SunmiSdkManage.getInstance().showWelcomImg();
       }

       @Override
       public void onSendFail(int errorId, String errorInfo) {
           Mtoast("副屏显示失败");
       }

       @Override
       public void onSendProcess(long totle, long sended) {

       }
   };

    Handler myHandler=new Handler();
    Runnable delayRun=new Runnable() {
        @Override
        public void run() {
            SunmiSdkManage.getInstance().showWelcomImg();
        }
    };


    private TextWatcher tWatcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence text, int i, int i1, int i2) {

        }

        @Override
        public  void onTextChanged(final CharSequence text, int start, int icount, int iafter) {

            if(start==17){
                et_pay.setText("");
                final String anthcode=text.toString();
                final int total_fee= (int) ((Double.parseDouble(total))*100);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        wxpay("就餐",total_fee,anthcode);
                    }
                }).start();

            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    public void wxpay(String body,int total_fee,String auth_code){

        try {
            Map<String,String> params=new HashMap<String,String>();
            String out_trade_no=WXPayUtil.generateNonceStr();

            params.put("appid",WXPayConstants.APP_ID);
            params.put("mch_id",WXPayConstants.MCH_ID);
            params.put("device_info",WXPayConstants.DEVICE_INFO);
            params.put("body",body);
            params.put("nonce_str",WXPayUtil.generateNonceStr());
            Log.e("lh", "nonce_str=="+WXPayUtil.generateNonceStr());
            params.put("out_trade_no",out_trade_no);
            Log.e("lh", "out_trade_no=="+out_trade_no);
            params.put("total_fee",total_fee+"");
            params.put("spbill_create_ip",spbill_create_ip);
            params.put("auth_code",auth_code);
            String  sign= WXPayUtil.generateSignature(params, WXPayConstants.WX_KEY);
            params.put("sign",sign);
            Log.e(TAG, "sign=="+sign );

            String content=WXPayUtil.mapToXml(params);
            Log.e(TAG, "content=="+content );
            String response=postData("https://api.mch.weixin.qq.com/pay/micropay",
                    content);
//        String response=WxPay.request(body,total_fee,auth_code);
//            LoggerFactory.getLogger(response);
            Log.e(TAG, "response=="+response );
            Map<String,String> maps =WXPayUtil.xmlToMap(response);
//            for (Map.Entry<String, String> entry : maps.entrySet()) {
//                Log.e(TAG, "getKey=="+entry.getKey() );
//                Log.e(TAG, "getValue=="+entry.getValue() );
////                entry.getKey();
////                entry.getValue();
//            }
            if(maps.get("return_code").equals("SUCCESS") && maps.get("result_code").equals("SUCCESS")){
                SunmiSdkManage.getInstance().showPrice("",
                        getString(R.string.pay_success), callback);
                Intent intent = new Intent(getApplicationContext(),PayresultActivity.class);
                intent.putExtra("balance","1");
                startActivity(intent);
                finish();

            }else{
               Mtoast(maps.get("result_code"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void addSqlite(String str){
        synchronized (str) {
            et_pay.setText("");
            long sysTime = System.currentTimeMillis();
            String id = SysTimeManage.getInstage().getOrderId(sysTime);
//			int type = SysTimeManage.getInstage().getOrderType(sysTime);
            String time = SysTimeManage.getInstage().getDateTime(sysTime);
            String date = SysTimeManage.getInstage().getDate(sysTime);
            U_SettletmentBean settl = new U_SettletmentBean
                    (id, str, diningType, total + "", time, 0, 0, 0, date, 0);
            boolean save = settl.save();
            if (save) {
                SunmiSdkManage.getInstance().showPrice("",
                        getString(R.string.pay_success), callback);
//				showBanlance();
                Toast.makeText(getApplicationContext(), "刷卡成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),
                        PayresultActivity.class);
//                intent.putExtra("type", Constant.URGENT_CARD_SUCCESS);
                startActivity(intent);
                finish();
            } else {
                Mtoast("刷卡失败");
            }
        }
    }

    private void otherPay(String card){
        et_pay.setText("");
        Call<String> call= HttpManage.getRequestApi().otherPay(
                SPManage.getInstance().getToken(),id,card,"");
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response,String base) {
                Gson gson=new Gson();

                Balance balanceBean=gson.fromJson(base,Balance.class) ;
//                Log.e(TAG, "bean.getData()=="+bean.getData().toString() );
                if(balanceBean.getType()==0){ //普通员工
                    SunmiSdkManage.getInstance().showPrice(getString(R.string.pay_success),
                            "余额:"+ balanceBean.getBalance(),
                            callback);
                }else if(balanceBean.getType()==1){ //临时卡
                    SunmiSdkManage.getInstance().showPrice(getString(R.string.pay_success),
                            "剩余次数:"+ balanceBean.getLeft(),
                            callback);
                }

                Intent intent = new Intent(getApplicationContext(),PayresultActivity.class);
                intent.putExtra("balance","1");
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int code, String error) {
                Mtoast(error);
                SunmiSdkManage.getInstance().showPrice("",error,
                        callback);
            }
        });
    }




    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_back:
                if(!Constant.URGENT_TYPE){
                    cancelOrder();
                }else {
                    SunmiSdkManage.getInstance().showWelcomImg();
                    finish();
                }

                break;
        }
    }


    @Override
    public void onBackPressed() {
        cancelOrder();
        super.onBackPressed();
    }
     /**取消订单*/
    private void cancelOrder(){
        Call<BaseBean<String>> call=HttpManage.getRequestApi().cancelOrder(
                SPManage.getInstance().getToken(),id);

        call.enqueue(new MyCallback<BaseBean<String>>() {
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {

            }

            @Override
            public void onError(int code, String error) {

            }
        });
        finish();
        SunmiSdkManage.getInstance().showWelcomImg();

    }

    public static String postData(String urlStr, String data){
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);

                conn.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            if(data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            Log.e("lh", "Error connecting to " + urlStr + ": " + e.getMessage());
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
}
